// pages/addDerivative/addDerivative.js
Page({
    data: {
        // IP选项
        ipOptions: [],
        ipIndex: -1,
        // 系列选项
        seriesOptions: [],
        seriesIndex: -1,
        seriesHidden: false,
        // 产品选项
        productOptions: [],
        productIndex: -1,
        productHidden: false,
        // 表单数据
        ipId: '',
        ipName: '',
        seriesId: '',
        seriesName: '',
        productId: '',
        productName: '',
        releaseDate: '',
        goodsName: '',
        goodsImage: '',
        goodsPrice: '',
        imagePaths: [],
        sellerName: '',
        sellerId: '',
        shipAddress: '',
        shippingFee: '',
        remark: '',
        // 选择器显示状态
        showIPPopup: false,
        showSeriesPopup: false,
        showProductPopup: false,
        showTimePopup: false,
        // 表单验证状态
        formValid: false,
        submitting: false,
        minDate: new Date(1990, 1, 1).getTime(),
        maxDate: new Date(2099, 12, 31).getTime(),
        currentDate: new Date().getTime(),
        formatter(type, value) {
            // 先验证value是否为有效数值
            // if (isNaN(value)) return '';
            if (type === 'year') {
                return `${value}年`;
            } else if (type === 'month') {
                return `${value}月`;
            } else if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
    },

    onLoad: function () {
        // 从本地存储获取卖家信息
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
            this.setData({
                sellerName: userInfo.nickName || '未设置用户名',
                sellerId: userInfo._id || ''
            });
        }
        // 调用云函数获取分类列表
        this.getTypeList();
    },
    // 显示时间选择器
    showTimePicker() {
        console.log(1);
        this.setData({
            showTimePopup: true
        });
    },

    // 关闭时间选择器
    onTimePopupClose() {
        this.setData({
            showTimePopup: false
        });
    },
    // 日期格式化函数
    formatDate(date) {
        let taskStartTime
        if (date.getMonth() < 9) {
            taskStartTime = date.getFullYear() + "-0" + (date.getMonth() + 1) + "-"
        } else {
            taskStartTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-"
        }
        if (date.getDate() < 10) {
            taskStartTime += "0" + date.getDate()
        } else {
            taskStartTime += date.getDate()
        }

        return taskStartTime;
    },
    // 时间选择器确认事件
    onTimePickerChange(event) {
        this.setData({
            releaseDate: this.formatDate(new Date(event.detail)),
            showTimePopup: false
        });
    },

    // 显示IP选择器
    showIPPicker() {
        console.log(1);
        this.setData({
            showIPPopup: true
        });
    },

    // 关闭IP选择器
    onIPPopupClose() {
        this.setData({
            showIPPopup: false
        });
    },

    // IP选择器确认事件
    onIPPickerChange(event) {
        const {
            value,
            index
        } = event.detail;
        console.log(event);
        this.setData({
            ipIndex: index,
            showIPPopup: false,
            ipId: value.id,
            ipName: value.name
        });
    },


    // 图片上传处理
    afterReadImage(event) {
        console.log(event);
        const {
            file
        } = event.detail;
        // 这里可以对图片进行一些预处理，例如压缩
        this.setData({
            imagePaths: [...this.data.imagePaths, file]
        });
    },
    // 获取IP列表
    getTypeList: function () {
        const that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        wx.cloud.callFunction({
            name: 'getTypeList',
        }).then(res => {
            wx.hideLoading();
            console.log(res);
            if (res.result && res.result.success) {
                // 成功获取IP列表
                that.setData({
                    ipOptions: res.result.data
                });
            } else {
                wx.showToast({
                    title: '获取IP列表失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('调用云函数失败', err);
            wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
            });
        });
    },

    // 发售时间变化处理
    handleReleaseDateChange: function (e) {
        this.setData({
            releaseDate: e.detail.value
        });
    },

    // 商品名称输入处理
    handleGoodsNameChange: function (e) {
        this.setData({
            goodsName: e.detail
        });
    },

    // 商品价格输入处理
    handlePriceChange: function (e) {
        console.log(e);
        // 限制只能输入数字和小数点
        let value = e.detail;
        value = value.replace(/[^\d.]/g, '');
        // 只允许一个小数点
        value = value.replace(/\.{2,}/g, '.');
        // 保证小数点只出现一次，而不能出现两次以上
        value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
        // 最多保留两位小数
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

        this.setData({
            goodsPrice: value
        });
    },

    // 发货地址输入处理
    handleShippingAddressChange: function (e) {
        console.log(e);
        this.setData({
            shipAddress: e.detail
        });
    },

    // 运费输入处理
    handleFreightChange: function (e) {
        // 限制只能输入数字和小数点
        let value = e.detail;
        value = value.replace(/[^\d.]/g, '');
        // 只允许一个小数点
        value = value.replace(/\.{2,}/g, '.');
        // 保证小数点只出现一次，而不能出现两次以上
        value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
        // 最多保留两位小数
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

        this.setData({
            shippingFee: value
        });
    },

    // 商品描述输入处理
    handleDescriptionChange: function (e) {
        this.setData({
            remark: e.detail
        });
    },



    // 表单验证
    validateForm: function () {
        const {
            ipName,
            releaseDate,
            goodsName,
            goodsPrice,
            imagePaths,
            shipAddress,
            shippingFee,
            remark
        } = this.data;
        const errors = {
            ipName,
            releaseDate,
            goodsName,
            goodsPrice,
            imagePaths,
            shipAddress,
            shippingFee,
            remark
        };
        let isValid = true;

        // 验证IP
        if (ipName === '') {
            errors.ipName = '请选择分类';
            isValid = false;
        } 
        // 验证商品名称
        if (!goodsName.trim()) {
            errors.goodsName = '请输入商品名称';
            isValid = false;
        } else if (goodsName.length > 50) {
            errors.goodsName = '商品名称不能超过50个字符';
            isValid = false;
        }

        // 验证商品价格
        if (!goodsPrice) {
            errors.goodsPrice = '请输入商品价格';
            isValid = false;
        } else if (isNaN(parseFloat(goodsPrice)) || parseFloat(goodsPrice) <= 0) {
            errors.price = '请输入有效的价格';
            isValid = false;
        }

        // 验证图片
        if (imagePaths.length === 0) {
            errors.images = '请上传商品图片';
            isValid = false;
        }

        // 验证发货地址
        if (!shipAddress.trim()) {
            errors.shipAddress = '请输入发货地址';
            isValid = false;
        }

        // 验证运费
        if (!shippingFee && shippingFee !== '0') {
            errors.shippingFee = '请输入运费';
            isValid = false;
        } else if (isNaN(parseFloat(shippingFee)) || parseFloat(shippingFee) < 0) {
            errors.shippingFee = '请输入有效的运费';
            isValid = false;
        }

        this.setData({
            formValid: isValid
        });
        return isValid;
    },

    // 上传图片到云存储 - 优化版本
    uploadImages: function (tempFilePaths) {
        console.log(tempFilePaths);
        // 检查是否有图片需要上传
        if (!tempFilePaths || tempFilePaths.length === 0) {
            return Promise.resolve([]);
        }

        // 创建上传任务数组
        const uploadPromises = tempFilePaths.map((urls, index) => {
            let filePath = urls.url
            // 生成唯一云存储路径
            const cloudPath = `goods_images/${Date.now()}_${index}${filePath.match(/\.[^.]+$/)[0]}`;

            // 返回上传Promise
            return wx.cloud.uploadFile({
                cloudPath,
                filePath,
            }).then(res => {
                console.log(`第${index+1}张图片上传成功`, res.fileID);
                return res.fileID;
            }).catch(err => {
                console.error(`第${index+1}张图片上传失败:`, err);
                return null; // 失败时返回null，不中断整体上传
            });
        });
        console.log(uploadPromises);
        // 等待所有上传任务完成
        return Promise.allSettled(uploadPromises)
            .then(results => {
                // 过滤掉失败的上传
                const successfulUploads = results.filter(fileID => fileID !== null);

                // 检查是否有上传失败
                const failedCount = results.length - successfulUploads.length;
                if (failedCount > 0) {
                    wx.showToast({
                        title: `部分图片上传失败(${failedCount}张)`,
                        icon: 'none',
                        duration: 3000
                    });
                }
                console.log(successfulUploads);
                return successfulUploads;
            })
            .catch(err => {
                console.error('图片上传过程中发生错误：', err);
                wx.showToast({
                    title: '图片上传失败，请重试',
                    icon: 'none',
                    duration: 3000
                });
                throw err;
            });
    },

    

    // 预览图片
    previewImages: function (imagePaths) {
        if (!imagePaths || imagePaths.length === 0) return;

        wx.previewImage({
            urls: imagePaths.url,
            current: imagePaths[0]
        });
    },
    // 删除图片
    deleteImage: function (e) {
        const index = e.detail.index;
        const imagePaths = [...this.data.imagePaths];
        if (index >= 0 && index < imagePaths.length) {
            imagePaths.splice(index, 1);
            console.log(imagePaths);
            this.setData({
                imagePaths: imagePaths
            });
        }
    },

    // 提交表单
    submitForm: function () {
        console.log(this.data);
        const that = this;

        // 表单验证
        if (!this.validateForm()) {
            wx.showToast({
                title: '请补全信息',
                icon: 'none',
                duration: 3000
            });
            return;
        }
        this.setData({
            submitting: true
        });
        // 显示加载提示
        wx.showLoading({
            title: '提交中...',
            mask: true
        });
        // 上传图片到云存储
        this.uploadImages(this.data.imagePaths)
            .then(fileIDs => {
                console.log(fileIDs);
                let str = ''
                fileIDs.forEach(f => {
                    str += f.value + ','
                })
                console.log(str);
                // 准备提交数据
                const formData = {
                    ipId: this.data.ipId,
                    ipName: this.data.ipName,
                    seriesId: this.data.seriesId,
                    seriesName: this.data.seriesName,
                    productId: this.data.productId,
                    productName: this.data.productName,
                    releaseTime: this.data.releaseDate,
                    goodsName: this.data.goodsName,
                    goodsPrice: parseFloat(this.data.goodsPrice),
                    sellerName: this.data.sellerName,
                    sellerId: this.data.sellerId,
                    shipAddress: this.data.shipAddress,
                    shippingFee: parseFloat(this.data.shippingFee),
                    remark: this.data.remark,
                    goodsImage: str.slice(0, -1),
                    createTime: new Date().toISOString(),
                    status: true, // 默认为上架状态
                    type:'derivative'
                };

                // 调用云函数上传商品信息
                return wx.cloud.callFunction({
                    name: 'uploadGoods',
                    data: formData
                });
            })
            .then(res => {
                console.log(res);
                wx.hideLoading();
                if (res.result && res.result.success) {
                    // 上传成功
                    wx.showToast({
                        title: '商品上传成功！',
                        icon: 'none',
                    });
                    // 上传成功后刷新页面（重新加载数据）
                    this.refreshPageData();
                    // // 延迟后返回上一页
                    // setTimeout(() => {
                    //     wx.navigateBack({
                    //         delta: 1
                    //     });
                    // }, 2000);
                } else {
                    // 上传失败
                    const errorMsg = res.result && res.result.message ? res.result.message : '上传失败，请重试';
                    wx.showToast({
                        title: errorMsg,
                        icon: 'none',
                        duration: 3000
                    });
                }
            })
            .catch(err => {
                wx.hideLoading();
                console.error('提交表单失败：', err);
                wx.showToast({
                    title: '提交失败，请检查网络或稍后再试',
                    icon: 'none',
                    duration: 3000
                });
            })
            .finally(() => {
                this.setData({
                    submitting: false
                });
            });
    },

    // 刷新页面数据的方法
    refreshPageData: function () {
        // 重置表单数据
        this.setData({
            ipIndex: -1,
            seriesIndex: -1,
            productIndex: -1,
            ipId: '',
            ipName: '',
            seriesId: '',
            seriesName: '',
            productId: '',
            productName: '',
            releaseDate: '',
            goodsName: '',
            goodsPrice: '',
            imagePaths: [],
            shipAddress: '',
            shippingFee: '',
            remark: ''
        });

        // 重新获取IP列表（如果需要）
        this.getTypeList();

        // 可以根据需要添加其他刷新逻辑
        console.log('页面数据已刷新');
    }
});